<template>
  <div class="edit-address-form">
    <!-- 顶部头 -->
    <header class="header-fiexed">
      <van-nav-bar :title="getTitle"
                   left-arrow
                   @click-left="$router.go(-1)" />
    </header>

    <!-- 表单内容 -->
    <van-form @submit="submit">
      <div class="flex justify-between selectAddress">
        <div class="lable">收货地址:</div>
        <div class="input-main flex justify-start"
             @click="showMap = true">
          <van-icon name="location-o padding-icon"></van-icon>
          <van-field v-model="address_info.area_info"
                     type="text"
                     placeholder="请选择"
                     readonly
                     :rules="[{ required: true, message: '请选择收货地址' }]" />
        </div>
        <van-icon name="arrow"></van-icon>
      </div>
      <van-field v-model="address_info.address_detail"
                 type="text"
                 label="详细地址:"
                 placeholder="如道路、门牌号、小区、楼栋号、单元室等"
                 :rules="[{ required: true, message: '请填写详细地址' }]" />
      <van-field v-model="address_info.address_realname"
                 type="text"
                 label="联系人:"
                 placeholder="请补充联系人的姓名"
                 :rules="[{ required: true, message: '请填写联系人名称' }]" />
      <van-field v-model="address_info.address_mob_phone"
                 type="number"
                 label="手机号码:"
                 placeholder="请填写收货人手机号码"
                 :rules="phoneRules" />
      <van-switch-cell v-model="address_info.address_is_default"
                       active-color="#E9AC64"
                       title="设为默认地址" />
      <van-button round
                  size="large"
                  class="save-btn">保存地址</van-button>
    </van-form>

    <!-- 弹出地图选择 -->
    <van-popup v-model="showMap"
               position="bottom">
      <van-picker show-toolbar
                  title="选择地址"
                  value-key="area_name"
                  :columns="area_list"
                  @confirm="callback"
                  @cancel="showMap = false"
                  :loading="area_list.length === 0" />
    </van-popup>

  </div>
</template>

<script>
import { getAreaTree } from '@/api/common'
import { getAddressInfo, addAddress, editAddress } from '@/api/memberAddress'
import { phoneRules } from '@/utils/formRules'
// 禁止安卓下拉刷新
window.android && window.android.appCanRefresh(0)
export default {
  name: 'AddressForm',
  data() {
    return {
      phoneRules: Object.freeze(phoneRules),
      showMap: false, // 显示选择地址弹窗
      keyword: '', // 地址
      area_list: [], // 全国省市区位置
      address_id: 0,
      address_info: {
        address_realname: '',
        address_mob_phone: '',
        address_detail: '',
        address_is_default: true,
        area_info: '',
        province_id: 0,
        city_id: 0,
        area_id: 0,
        address_longitude: 0,
        address_latitude: 0
      }
    }
  },

  computed: {
    /**
     * 判断当前编辑的模式
     */
    isAddMode() {
      return this.$route.query.action === 'add' // 获取当前编辑模式
    },
    /**
     * 获取顶部标题
     */
    getTitle() {
      return this.isAddMode ? '新增地址' : '修改收货地址'
    }
  },

  created() {
    if (!this.isAddMode) {
      this.address_id = this.$route.query.address_id
      getAddressInfo(this.address_id)
        .then(res => {
          this.address_info = res.result.address_info
          if (res.result.address_info.daddress_isdefault === '1') {
            this.address_info.daddress_isdefault = true
          } else {
            this.address_info.daddress_isdefault = false
          }
        })
        .catch(function(error) {
          this.$toast({
            type: 'fail',
            message: error.message
          })
        })
    }
  },

  mounted() {
    // 获取全国地址列表
    getAreaTree().then(res => {
      var areaListStr = JSON.stringify(res.result.area_list)
      this.area_list = JSON.parse(areaListStr.replace(/child/g, 'children'))
    })
  },
  methods: {
    /**
     * 保存地址
     */
    submit() {
      var submitRes = this.isAddMode
        ? addAddress(this.address_info)
        : editAddress(this.address_info, this.isAddMode ? 0 : this.address_id)

      submitRes
        .then(res => {
          this.$toast({
            type: 'success',
            message: res.message || '操作成功',
            duration: 3000,
            onClose: () => {
              this.updateSelectedAddress()
            }
          })
        })
        .catch(error => {
          this.$toast({
            type: 'fail',
            message: error.message
          })
        })
    },

    /**
     * 回调页面
     */
    updateSelectedAddress() {
      let isFromCheckout = this.$route.query.isFromCheckout
      let goBackLevel = this.$route.query.goBackLevel
        ? this.$route.query.goBackLevel
        : -1
      if (isFromCheckout) {
        this.$router.go(goBackLevel)
      } else {
        this.$router.go(-1)
      }
    },

    // 地图选择回调
    callback(mapData, mapIndex) {
      this.showMap = false

      var areaList = this.area_list[mapIndex[0]]

      this.address_info.province_id = areaList.area_id
      this.address_info.city_id = areaList.children[mapIndex[1]].area_id

      if (areaList.children[mapIndex[1]].children[mapIndex[2]]) {
        this.address_info.area_id =
          areaList.children[mapIndex[1]].children[mapIndex[2]].area_id
      } else {
        this.address_info.area_id = this.address_info.city_id
      }

      this.address_info.area_info = mapData.join(' ') // 省市区中文
    }
  }
}
</script>

<style lang="scss">
.edit-address-form {
  .selectAddress {
    font-size: 14px;
    padding: 0px 15px;
    position: relative;
    background-color: #fff;
    .padding-icon {
      padding-top: 0.6rem;
    }
    &::after {
      content: ' ';
      position: absolute;
      pointer-events: none;
      left: 15px;
      right: 0;
      bottom: 0;
      -webkit-transform: scaleY(0.5);
      transform: scaleY(0.5);
      border-bottom: 1px solid #ebedf0;
    }
    .lable {
      width: 90px;
      padding-top: 0.6rem;
    }
    .input-main {
      flex: 1;
      .address {
        margin-left: 5px;
      }
    }
    .van-field__body input::placeholder {
      color: #ccc;
    }
  }

  .save-btn {
    background-color: $mainColor;
    color: #fff;
    width: 95%;
    margin: 30px 2.5%;
  }
}
</style>
